﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataMgr.ui_control
{
    class ListViewColumnSorter : IComparer
    {
        private int columnToSort;
        private SortOrder orderOfSort;
        private CaseInsensitiveComparer objectCompare;
        public ListViewColumnSorter()
        {
            columnToSort = 0;
            orderOfSort = SortOrder.None;
            objectCompare = new CaseInsensitiveComparer();
        }


        int IComparer.Compare(object x, object y)
        {
            int result = 0;
            ListViewItem lx = (ListViewItem)x;
            ListViewItem ly = (ListViewItem)y;
            string xtext = lx.SubItems[columnToSort].Text;
            string ytext = ly.SubItems[columnToSort].Text;
            int xx = 0, yy = 0;
            if (int.TryParse(xtext, out xx) && int.TryParse(ytext, out yy))
                result = xx.CompareTo(yy);
            else
                result = xtext.CompareTo(ytext);
            if (orderOfSort == SortOrder.Ascending)
                return result;
            else if (orderOfSort == SortOrder.Descending)
                return -result;
            else
                return 0;
        }
        public int sortColumn
        {
            set { columnToSort = value; }
            get { return columnToSort; }
        }
        public SortOrder order
        {
            set { orderOfSort = value; }
            get { return orderOfSort; }
        }



    }

    class ListViewHelper
    {
        public ListViewHelper() { }
        public static void listView_columnClick(object sender, ColumnClickEventArgs e)
        {

            ListView lv = sender as ListView;
            lv.Cursor = Cursors.Hand;
            if (e.Column == ((ListViewColumnSorter)lv.ListViewItemSorter).sortColumn)//排序方式
            {
                if (((ListViewColumnSorter)lv.ListViewItemSorter).order == SortOrder.Ascending)
                    ((ListViewColumnSorter)lv.ListViewItemSorter).order = SortOrder.Descending;
                else
                    ((ListViewColumnSorter)lv.ListViewItemSorter).order = SortOrder.Ascending;

            }
            else
            {
                ((ListViewColumnSorter)lv.ListViewItemSorter).sortColumn = e.Column;
                ((ListViewColumnSorter)lv.ListViewItemSorter).order = SortOrder.Ascending;
            }
            lv.Sort();
        }
    }
}
